#include "customizelineedit.h"
#include "singleton.h"
#include "chatdialog.h"

#include <QAction>

CustomizeLineEdit::CustomizeLineEdit(QWidget *parent)
    : QLineEdit(parent)
{
    // 设置可输入的最大字符数为20
    setMaxLength(20);

    // 在输入框头部添加图标
    _AddIconToHead(":/res/search.png", "搜索...");

    // 在输入框尾部添加清除文字图标（默认为透明图标，有文字时显示）
    _AddClearIconToTail(":/res/close_transparent.png");

    _SetConnect();
}

void CustomizeLineEdit::_SetConnect()
{
    // 失去焦点时，清除文字
    connect(this, &CustomizeLineEdit::editingFinished, this, [this]() {
        clear();
    });
}

void CustomizeLineEdit::focusOutEvent(QFocusEvent *e)
{
    // 调用基类的 focusOutEvent 方法，确保焦点事件被正确处理
    QLineEdit::focusOutEvent(e);
    emit sig_focus_out();
}

void CustomizeLineEdit::_AddIconToHead(const QString &iconPath, const QString &text)
{
    QAction *action = new QAction(this);
    action->setIcon(QIcon(iconPath));
    addAction(action, QLineEdit::LeadingPosition);
    setPlaceholderText(text);
}


// 在输入框尾部添加清除文字图标
void CustomizeLineEdit::_AddClearIconToTail(const QString &iconPath)
{
    QAction *action = new QAction(this);
    action->setIcon(QIcon(iconPath));
    addAction(action, QLineEdit::TrailingPosition);

    // 设置清除图标事件
    connect(this, &QLineEdit::textChanged, this, [action](const QString &text) {
        if (text.isEmpty()) {
            action->setIcon(QIcon(":/res/close_transparent.png"));
        } else {
            // 有文字时，显示清除图标
            action->setIcon(QIcon(":/res/close_search.png"));
        }
    });

    // 设置清除图标点击事件
    connect(action, &QAction::triggered, this, [this]() {
        clear();
        this->clearFocus(); // 清除文字后，移除焦点
        //设置聊天窗口关闭搜索框
        MagicSingleton<ChatDialog>::GetInstance()->ShowSearch(false);
    });
}
